package org.real.guetshop.mapper;

import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.*;
import org.real.guetshop.pojo.dto.OrderPageDTO;
import org.real.guetshop.pojo.entity.Order;
import org.real.guetshop.pojo.entity.RedisOrder;
import org.real.guetshop.pojo.vo.OrderOldVO;

import java.time.LocalDateTime;
import java.util.List;

@Mapper
public interface OrderMapper {

    /**
     * 新增订单
     * @param order
     */
    @Insert("insert into orders (order_number, number, user_id,product_id,name,store_id, phone, address, amount, status, order_time) " +
            "VALUES (#{orderNumber},#{number},#{userId},#{productId},#{name},#{storeId},#{phone},#{address},#{amount},#{status},#{orderTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(Order order);

    /**
     * 订单完成
     */
    @Update("update orders set end_time = #{endTime},status = #{status} where order_number = #{orderNumber}")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void finish(Order order);

    /**
     * 获取历史订单
     * @param userId
     * @return
     */
    @Select("select * from orders where user_id = #{userId}")
    List<OrderOldVO> getHistory(Integer userId);

    /**
     * 获取订单的商品
     * @return
     */
//    @Select("select * from order_goods where order_id = #{orderId}")
//    List<OrderGood> getHistoryGood(Integer orderId);

    /**
     * 根据订单号获取订单
     * @param orderNumber
     * @return
     */
    @Select("select o.*,u.name as username,p.unit from orders o " +
            "INNER join user u on o.user_id = u.id " +
            "INNER join products p on o.product_id = p.id" +
            " where o.order_number = #{orderNumber}")
    Order getByNumber(String orderNumber);

    /**
     * 商家订单分页查询
     * @param orderPageDTO
     * @param storeId
     * @return
     */
    Page<Order> page(OrderPageDTO orderPageDTO, Integer storeId);

    @Select("select * from orders where status = #{status}")
    List<Order> getByStatus(Integer status);

    /**
     * 删除已完成订单
     * @param order
     */
    @Delete("delete from orders where id = #{order.id} and orders.end_time < #{nowTime}")
    void deleteByOverTime(Order order, LocalDateTime nowTime);

    /**
     * 根据id获取订单
     *
     * @param userId
     * @return
     */
    @Select("select o.*,u.name as username, p.unit, p.price, p.image from orders o" +
            " INNER JOIN user u on o.user_id = u.id" +
            " INNER JOIN products p on o.product_id = p.id" +
            " where user_id = #{userId}")
    List<RedisOrder> selectBatch(Integer userId);
}
